from web_ui.frame.utils.log_utils import logger


def repeat_click(by, locate=None, max_click=5):
    def __iner(driver):
        actual_click = 1
        while actual_click <= max_click:
            try:
                driver.find_element(by, locate).click()
                logger.info(f"第{actual_click}点击{locate}成功")
                return True
            except Exception:
                logger.info(f"第{actual_click}点击{locate}失败")
                actual_click += 1
        logger.info(f"达到最大点击次数{max_click}")
        raise Exception

    return __iner


def click_exception_user_defined(by, locate=None, max_attempts=10):
    def _inner(driver):
        # 多次点击按钮
        actul_attempts = 0  # 实际点击次数
        while actul_attempts < max_attempts:
            # 进行点击操作
            actul_attempts += 1  # 每次循环，实际点击次数加1
            try:
                # 如果点击过程报错，则直接执行 except 逻辑，并切继续循环
                # 没有报错，则直接return 循环结束
                if locate:
                    driver.find_element(by, locate).click()
                    logger.info(f"第{actul_attempts}次点击成功")
                else:
                    driver.find_element(*by).click()
                    logger.info(f"第{actul_attempts}次点击成功")
                return True
            except Exception:
                logger.info(f"第{actul_attempts}次点击失败")
        # 当实际点击次数大于最大点击次数时，结束循环并抛出异常
        raise Exception("超出了最大点击次数")

    return _inner
